
import React, { useEffect, useState } from "react";

/** 监控元素宽高 */
export function useElementResize<H extends HTMLElement>() {

    const [element, setElement] = useState<H | null>(null);
    const [width, setWidth] = useState<number>(0);
    const [height, setHeight] = useState<number>(0);

    const onRef = React.useCallback((node: H | null) => { setElement(node) }, []);

    useEffect(() => {
        const handleResize = (entries: ResizeObserverEntry[]) => {
            for (const entry of entries) {
                setWidth(entry.contentRect.width);
                setHeight(entry.contentRect.height);
            }
        };

        const resizeObserver = new ResizeObserver(handleResize);
        if (element) {
            resizeObserver.observe(element);
        }

        return () => {
            if (element) {
                resizeObserver.unobserve(element);
            }
        };
    }, [element]);

    return {
        /** ref */
        onRef,

        /** 监控元素的宽度 */
        width,

        /** 监控元素的高度 */
        height,
    };
}

/**
 * 计算项目宽度
 * @param width 容器宽度
 * @param minWidth 单个项目最小宽度
 */
export function useItemWidth(width: number, minWidth: number = 300) {

    const [itemWidth, setItemWidth] = useState<number>(0);
    const [rowQuantity, setRowQuantity] = useState<number>(0);

    useEffect(() => {
        if (!width) return;
        const t = Math.floor(width / minWidth);
        const w = Math.floor(width / t);
        setRowQuantity(t);
        setItemWidth(w);
    }, [width, minWidth]);

    return {

        /** 一个项目的宽度 */
        itemWidth,

        /** 一行可以多少个 */
        rowQuantity,
    }
}